package com.gears_software.sxdc.dccx.data.service;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.application.DCCXApplication_;
import com.gears_software.sxdc.dccx.data.db.DBUtils;
import com.gears_software.sxdc.dccx.data.db.DBUtils_;
import com.gears_software.sxdc.dccx.data.finder.IMemberFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.MemberModel;
import com.gears_software.sxdc.dccx.data.model.MsgModel;
import com.gears_software.sxdc.dccx.data.model.NoticeModel;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.sharedPreference.DCCXSp_;
import com.gears_software.sxdc.dccx.ui.activity.MainActivity_;
import com.gears_software.sxdc.dccx.ui.activity.WaitForJieJiaActivity_;
import com.gears_software.sxdc.dccx.ui.activity.WaitForJieJiaNewActivity_;
import com.gears_software.sxdc.dccx.ui.event.LogoutDriverMemberEvent;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.gears_software.sxdc.dccx.ui.util.OttoBus;
import com.gears_software.sxdc.dccx.ui.util.OttoBus_;
import com.gears_software.sxdc.dccx.ui.util.YuYin;
import com.github.mzule.activityrouter.router.Routers;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.j256.ormlite.stmt.query.In;
import com.orhanobut.logger.Logger;
import com.sdsmdg.tastytoast.TastyToast;
import com.umeng.message.UmengBaseIntentService;
import com.umeng.message.UmengMessageService;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import org.android.agoo.common.AgooConstants;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EService;
import org.androidannotations.annotations.RootContext;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.androidannotations.rest.spring.annotations.RestService;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import static anet.channel.util.Utils.context;

/**
 * Created by chezhenzhen on 2017/10/9.
 */

public class MyPushIntentService extends UmengMessageService {
    String routerUrl = "";
    DBUtils dbUtils;
    DCCXSp_ sp;

    @Override
    public void onMessage(Context context, Intent intent) {
        try {
            dbUtils = DBUtils_.getInstance_(context);
            sp = new DCCXSp_(context);
            String message = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
            UMessage msg = new UMessage(new JSONObject(message));
            String extraStr = "";
            if (msg.extra != null) {
                Map<String, String> extraMap = msg.extra;
                if (extraMap != null) {
                    extraStr = extraMap.get("location");
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            try {
                if (msg.custom != null && !msg.custom.equals("")) {
                    Map map = mapper.readValue(msg.custom, Map.class);
                    if (map.get("router") != null) {
                        routerUrl = "gears_dccx://" + map.get("router").toString();
                    } else {
                        routerUrl = "gears_dccx://main";
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            switch (msg.display_type) {
                case "notification":
                    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
                    mBuilder.setContentTitle(msg.title)//设置通知栏标题
                            .setContentText(msg.text) //设置通知栏显示内容
                            .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                            .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                            .setTicker(msg.ticker)
                            .setContentIntent(getPendingIntent(msg, context))
                            .setDefaults(Notification.DEFAULT_ALL)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                            //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
                            .setSmallIcon(R.mipmap.ic_launcher);//设置通知小ICON
                    mNotificationManager.notify(1, mBuilder.build());

                    break;
                case "custom":
                    MsgModel msgModel = new MsgModel();
                    if (msg.custom != null && !msg.custom.equals("")) {
                        Gson gson = new GsonBuilder().create();
                        msgModel = gson.fromJson(msg.custom, MsgModel.class);
                    }

                    if (msgModel.getType() == 99) {
                        //TODO 跳转到mainactivity 判断是否要顶下线
                        sp.token().put("");
                        sp.refreshToken().put("");
                        sp.userId().put("");
                        Intent intent2 = new Intent(context, MainActivity_.class);
                        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent2.putExtra("isLogout", "1");
                        startActivity(intent2);

                    } else if (msgModel.getType() == -1) {
                        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                        String runningActivity = activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
                        String str = runningActivity.substring(runningActivity.lastIndexOf(".") + 1);
                        if (str.equals("WaitForJieJiaNewActivity_")) {
                            Intent intent1 = new Intent(context, WaitForJieJiaNewActivity_.class);
                            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent1.putExtra("msgModel", msgModel);
                            intent1.putExtra("extraStr", extraStr);
                            startActivity(intent1);
                        } else {
                            sp.orderid().put("0");
                            YuYin yuYin = new YuYin(context);
                            yuYin.yuyinbobao("订单已被平台取消");
                        }
                    } else {
                        Intent intent1 = new Intent(context, WaitForJieJiaNewActivity_.class);
                        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent1.putExtra("msgModel", msgModel);
                        intent1.putExtra("extraStr", extraStr);
                        startActivity(intent1);
                    }

                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private PendingIntent getPendingIntent(UMessage msg, Context context) {
        //保存本地ormlite
        NoticeModel noticeModel = new NoticeModel();
        noticeModel.setTitle(msg.title);
        noticeModel.setContent(msg.text);
        if (!sp.userId().get().equals("")) {
            noticeModel.setUserId(sp.userId().get());
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(System.currentTimeMillis());
        noticeModel.setCreateDate(sf.format(date));
        dbUtils.insertNotice(noticeModel);

        Intent intent = Routers.resolve(context, routerUrl);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        return pendingIntent;
    }


}
